﻿package Socket
{
	import flash.events.EventDispatcher;
	import flash.events.Event;
	import flash.net.Socket;
	import flash.events.IOErrorEvent;
	import flash.events.SecurityErrorEvent;
	import flash.events.TimerEvent;
	import flash.utils.Timer;
	import flash.utils.Endian;
	import flash.system.Security;
	import Utils.BindableUnsignedInteger;
	import Utils.BindableString;

	public class ConnectionWatcher extends Contexted
	{
		//public static var MESSAGE:String = "message";

		var isConnected:Boolean = false;
		var timerKeepAlive:Timer = new Timer(3000,0);
		public var port:BindableUnsignedInteger;
		public var address:BindableString;
		public var socket:Socket;

		public function ConnectionWatcher(context:Context)
		{
			super(context);
			this.address = new BindableString();
			this.port = new BindableUnsignedInteger();
			timerKeepAlive.addEventListener("timer", keepAlive);

			socket = new Socket();
			socket.endian = Endian.LITTLE_ENDIAN;
			socket.addEventListener(Event.CONNECT , this.onConnect);
			socket.addEventListener(Event.CLOSE , this.closeHandler);

			socket.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
			socket.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler);
		}

		public function connect(event:Event):void
		{/*
			Security.loadPolicyFile("http://" + address.data + "/crossdomain.xml");
			Security.allowDomain(address.data);*/
			socket.connect(address.data,port.data);
			trace("Connecting...");
		}

		public function onConnect(event:Event):void
		{
			isConnected = true;
			timerKeepAlive.start();
			context.sender.onSendKey();
		}

		function closeHandler(event:Event):void
		{
			trace("closeHandler: " + event);
			trace("Deconnecte");
			timerKeepAlive.stop();
			context.screen.display_connection_screen();
		}

		function ioErrorHandler(event:IOErrorEvent):void
		{
			trace("ioErrorHandler: " + event);
		}

		function securityErrorHandler(event:SecurityErrorEvent):void
		{
			trace("securityErrorHandler: " + event);
		}
		/*
		private function send(message:String):void
		{
		dispatchEvent(new MessageEvent(ConnectionWatcher.MESSAGE,message));
		}
		*/
		function keepAlive(e:TimerEvent):void
		{
			trace("Keep Alive");
			socket.writeByte(0xFF);
			socket.flush();
		}

	}

}